package cn.liuwenlin.mq.listener;

import cn.liuwenlin.mq.entity.Girl;
import com.sun.corba.se.impl.oa.poa.ActiveObjectMap;
import org.apache.activemq.command.ActiveMQObjectMessage;

import javax.jms.*;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

/**
 * @author 276834
 */
public class MessageListener implements javax.jms.MessageListener {

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    private Session session;

    @Override
    public void onMessage(Message message) {
        try {
            if(message instanceof TextMessage){
                TextMessage msg = (TextMessage)message;
                System.out.println("---TextMessage---");
                System.out.println("receive msg:" + msg.getText());
                System.out.println("---Back message to producer---");
                MessageProducer producer = session.createProducer(session.createQueue("activemq"));
                TextMessage backMsg = session.createTextMessage("back msg");
                backMsg.setJMSCorrelationID(msg.getJMSCorrelationID());
                backMsg.setStringProperty("selector", "recv");
                producer.send(backMsg);
            } else if (message instanceof BytesMessage) {
                BytesMessage msg = (BytesMessage)message;
                //将字节数组写入文件,追加方式
                FileOutputStream outputStream = new FileOutputStream("D:/byte.txt", true);
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
                byte[] buff = new byte[1024];
                int result = 0;
                System.out.println("---ByteMessage---");
                while((result = msg.readBytes(buff)) != -1){
                    System.out.println("receive msg:" + new String(buff, 0 , result));
//                    outputStream.write(buff, 0 ,result);
                    writer.append(new String(buff, 0 , result));
                }
                writer.append("\n");
                writer.flush();
            } else if (message instanceof MapMessage){
                MapMessage msg = (MapMessage)message;
                System.out.println("---MapMessage---");
                System.out.println("receive msg: name " + msg.getString("name"));
                System.out.println("receive msg: age " + msg.getString("age"));
                System.out.println("receive msg: price " + msg.getString("price"));
            } else if (message instanceof ObjectMessage){
                Girl girl = (Girl) ((ActiveMQObjectMessage) message).getObject();
                System.out.println("---ObjectMessage---");
                System.out.println("receive object: " + girl);
            } else {
                System.out.println("---Message not matched---");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
